//
//  TXYRequestManger.m
//  FunnyVideo
//
//  Created by 李鑫 on 15/8/26.
//  Copyright © 2015年 NewEggTech. All rights reserved.
//

#import "TXYRequestManger.h"
#import "ASIFormDataRequest.h"
#import "TXYRespCode.h"
#import "TXYManger.h"
#import "GiFHUD.h"
#import "NSDictionary+JSON.h"

@interface TXYRequestManger () <ASIHTTPRequestDelegate>

@end

@implementation TXYRequestManger
@synthesize cachedPersSig;

+ (TXYRequestManger *)sharedRequestManger{
    static dispatch_once_t onceToken;
    static TXYRequestManger *manger;
    dispatch_once(&onceToken, ^{
        manger = [[TXYRequestManger alloc] init];
    });
    
    return manger;
}
- (NSString *)requestSignatureBucketName:(NSString *)bucket type:(TXYSignatureType)type{
    
    
    //ASIHTTPRequest Instance
    NSString *sigReqURLStr = @"http://1.btcnotification.sinaapp.com/getSignature.php";
    
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:sigReqURLStr]];
    
    [request setRequestMethod:@"POST"];
    
    [request addPostValue:TXYSID forKey:@"sid"];
    
    [request addPostValue:bucket forKey:@"bucket"];
    
    [request addPostValue:type == TXYSignaturePersistant ? @0:@-1 forKey:@"sid_type"];
    
    [request startSynchronous];
    
    NSString *sig = [[NSString alloc]initWithData:[request responseData] encoding:NSUTF8StringEncoding];
    
    //cache persisstance signature
    (type == TXYSignatureOnce) ? :[self setCachedPersSig:sig];
    
    return sig;
}
/**
 *  请求并解析JSON数据
 *
 *  @param urlStr 请求的url
 *  @param sid    secret id来自腾讯云
 *  @param bodys  {@"bucket":@"bucketname",@"v_type":@"-1~6",@"limit":@"0-100..",@"offset":@"context(QCloud)"}
 *  @param block  回调参数(NSDictionary *data,NSUInteger httpcode,NSUInteger code,NSString* message)
 */
- (void)requestJSONDataFromURL:(NSString *)urlStr secretId:(NSString *)sid postBodys:(NSDictionary *)bodys completion:(TXYHTTPRequestBlock)block
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:urlStr]];
        
        //append post data
        for(NSString *key in [bodys allKeys])
        {
            NSLog(@"%@",key);
            [request addPostValue:[bodys objectForKey:key] forKey:key];
        }
        
        //append secret id
        [request addPostValue:sid forKey:@"sid"];
        
        [request setRequestMethod:@"POST"];
        
        //[request setPostFormat:ASIURLEncodedPostFormat];
        
        [request startSynchronous];
        
        NSData *jsonData = [[request responseString] dataUsingEncoding:NSUTF8StringEncoding];
        TXYResponse *txyresp = nil;
        if(jsonData)
        {
        
        NSDictionary *jsonDic = [NSDictionary convertJSONData:jsonData];
        
        NSLog(@"json Dictionary : %@",jsonDic);
        
        txyresp = [TXYResponse createResponseWith:[[jsonDic objectForKey:@"code"] unsignedIntegerValue] httpCode:[[jsonDic objectForKey:@"httpcode"] unsignedIntegerValue] message:[jsonDic objectForKey:@"message"] data:[jsonDic objectForKey:@"data"]];
        }
        else{
            txyresp = [TXYResponse createResponseWith:TXYRespCodeNoneData httpCode:TXYRespCodeNoneData message:@"未请求道数据,请检查网络连接" data:nil];
            [GiFHUD setGifWithImageName:@"pika.gif"];
            [GiFHUD show];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [GiFHUD dismiss];
            });
            
        }
        
        block(txyresp);
    });
}

- (void)setCachedPersSig:(NSString *)cachedPersSig_{
    cachedPersSig = cachedPersSig_;
}
@end



